//
//  DDQuestionView.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/7/6.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDQuestionView.h"
#import "UIImageView+WebCache.h"
#import "UFTextViewCustomToolbar.h"
#import "UIView+LoadFromNib.h"
#import "DDMediaVC.h"


#import "DDMediaIV.h"

#import "OptionImageView.h"

#define KEY_IMAGE @"IMAGE"
#define KEY_LABEL @"LABEL"
#define KEY_OPTION @"OPTION"
#define KEY_FILL @"FILL"
#define KEY_ANSWER_IMAGE @"ANSWER_IMAEG"
#define KEY_ANSWER_AUDIO @"ANSWER_AUDIO"

#define KEY_EXPLANATION @"EXPLANATION"
#define KEY_TIP @"TIP"

#define FILED_BODY_IMAGE @"IMAGE"
#define FILED_BODY_TEXT @"TEXT"

#define TOPIC_TYPE_SINGLE_SELECTION @"单选"
#define TOPIC_TYPE_MULTISELECT @"多选"
#define TOPIC_TYPE_JUDGMENT @"判断"
#define TOPIC_TYPE_INDEFINITE_ITEM @"不定项"
#define TOPIC_TYPE_FILL @"填空题"
#define TOPIC_TYPE_SHORT_ANSWER @"简答题"
@implementation DDQuestionView
#pragma mark - Lifecycle

- (id)initWithFrame:(CGRect)frame andColorViewData:(TNColorViewData *)colorViewData {
    
    self = [super initWithFrame:frame andColorViewData:colorViewData];
    
    if (self) {
        // Initialization code
        
        [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(reloadDataTagDB) name:@"reloadDataTagDB" object:nil];
        
        _topic = colorViewData.topic;
        NSLog(@"================%@=================", colorViewData.topic);
        _question = colorViewData.question;
        _page = colorViewData.page;
        _total = colorViewData.total;
        _showAnswer = colorViewData.showAnswer;
        
        _showAnswerLables = [NSMutableArray array];
        _explanations = [NSMutableArray array];
        
         _answers = [NSMutableArray array];
        
        self.backgroundColor = [UIColor whiteColor];
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.bounds.size.width, self.bounds.size.height - 64 - 88 ) style:UITableViewStyleGrouped];
        [self addSubview:self.tableView];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.tableHeaderView = [self headerView];
        
//        _tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissPopup)];
//        _tapRecognizer.numberOfTapsRequired = 1;
//        _tapRecognizer.delegate = self;
//        [self.tableView addGestureRecognizer:_tapRecognizer];
        
        //self.tableView.tableFooterView = [self createUI];
        
        _topicType = colorViewData.topicType;
        
        [self createUI];
        [self createData];
    }
    
    return self;
}
-(void)reloadDataTagDB
{
    [self.tableView reloadData];
}


#pragma mark - NSCopying

#pragma mark - Private methods
- (void)dismissPopup {
    [[NSNotificationCenter defaultCenter]  postNotificationName:@"dismissPopup" object:nil];
}

- (void)createUI
{
//    UIView *mediaView = [[DDMediaVC alloc] initWithNibName:@"DDMediaVC" bundle:nil].view;//[DDMediaView loadFromNib];
//     mediaView.frame = CGRectMake(0, self.frame.size.height - 88, self.frame.size.width, mediaView.frame.size.height);
//    mediaView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//    [self addSubview:mediaView];

}

- (void)createData
{
    
    _storeOptions = [NSMutableArray array];
    _datas = [NSMutableArray array];
    _keys = [NSMutableArray array];
    
   
    _answerIndex = 0;
    
    NSMutableArray *imageArray = [NSMutableArray array];
    //NSMutableArray *labelArray = [NSMutableArray array];
    NSMutableArray *optionArray = [NSMutableArray array];
    
    //DDTopicDataCellModel *model =  _topic.list[0];
    //DDTopicQuestion *question = model.questions[0];
    NSArray *bodyList = _question.body;
    _questionType = _question.typeName;
    
    optionArray = [NSMutableArray arrayWithArray:_question.options];

   //提取分组数据
    int cc = 0;
    for (DDTopicQuestionBody *body in bodyList) {
        if ([body.type isEqualToString:FILED_BODY_IMAGE]) {
            [imageArray addObject:body.url];
        }
        if ([body.type isEqualToString:FILED_BODY_TEXT]) {
            //[labelArray addObject:[NSString stringWithFormat:@"%ld.%@",(long)_page,body.text]];
            if (cc == 0) {
                _title = [NSString stringWithFormat:@"%ld.%@",(long)_page,body.text];
            }else{
                _title = body.text;
            }
            cc++;
            [imageArray addObject:_title];
        }
    }
    
    
    
   //分组
    if (imageArray.count > 0) {
        [_datas addObject:imageArray];
        [_keys addObject:KEY_IMAGE];
    }
//    if (labelArray.count > 0) {
//        [_datas addObject:labelArray];
//        [_keys addObject:KEY_LABEL];
//    }
    if (optionArray.count > 0) {
        [_datas addObject:optionArray];
        [_keys addObject:KEY_OPTION];
    }else{//有选项 和 填空题是互斥关系
    if ([_topicType isEqualToString:@"3"] || [_questionType isEqualToString:TOPIC_TYPE_FILL] || [_questionType isEqualToString:TOPIC_TYPE_SHORT_ANSWER]) {
        [_datas addObject:@""];
        [_keys addObject:KEY_FILL];
    }
    }

    if (_question.tip.length > 0 ) {
        [_datas addObject:_question.tip];
        [_keys addObject:KEY_TIP];
        
//        [_datas addObject:_question.explanation];
//        [_keys addObject:KEY_EXPLANATION];
    }
    
    
    
    [self.tableView reloadData];

}
- (void)reloadDataForAnswers:(UIImage *)image url:(NSString *)url
{
    if (image) {
        [_datas addObject:image];
        [_keys addObject:KEY_ANSWER_IMAGE];
    }
    [_answers addObject:url];
    
    [self.tableView reloadData];
    CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
    
    [self.tableView setContentOffset:offset animated:YES];
}
-(void)reloadDataForAnswers:(NSString *)path time:(NSString *)time url:(NSString *)url
{
    if (path) {
        NSString *temp = [NSString stringWithFormat:@"%@|%@",path,time];
        [_datas addObject:temp];
        [_keys addObject:KEY_ANSWER_AUDIO];
    }
    [_answers addObject:url];
    
    [self.tableView reloadData];
    CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
    [self.tableView setContentOffset:offset animated:YES];
}
- (UIView *)headerView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 32)];
    view.backgroundColor = RGB(248, 248, 248);
    
    UILabel *pageLabel = [[UILabel alloc] initWithFrame:CGRectMake( self.frame.size.width/2-5,5,self.frame.size.width , 32)];
    pageLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)_page,(long)_total];
    [view addSubview:pageLabel];
    return view;
}

#pragma mark - Public methods

#pragma mark - Custom Accessors

#pragma mark - Delegate methods
#pragma mark -UITableDelegate


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    _answerIndex = 0;
    return _datas.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = _datas[indexPath.section];
   // int tipHeight = 0;
    
    int textorImageheight = 0;
    if ([_keys[indexPath.section] isEqualToString:KEY_IMAGE]) {
//        if (_title) {
//            return 300 * (array.count -1) + [self autoLabelString:self.tableView string:_title].height + 50;
//        }
//        return (300 * array.count + 10);
        for (int i = 0; i < array.count; i++) {
            NSString *string = array[i];
           if ([string rangeOfString:@"http://"].location != NSNotFound &&([string rangeOfString:@"jpg"].location != NSNotFound || [string rangeOfString:@"png"].location != NSNotFound)) {
                textorImageheight += 300;
            }else{
                textorImageheight += [self autoLabelString:self.tableView string:string].height + 5;
            }
        }
        
        return textorImageheight+20;
        
    }
//    else if ([_keys[indexPath.section] isEqualToString:KEY_LABEL])
//    {
//        return 100 * array.count;
//    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_OPTION])
    {
        NSInteger height = 54*array.count + 70;
        
        if (_showAnswer&&[_questionType isEqualToString:TOPIC_TYPE_MULTISELECT]) {
            height += 100;
        }
        
        for (DDTopicQuestionOption *option in array) {
            if (option.content.count > 0) {
                DDTopicQuestionOptionContent *content = option.content[0];
               height += [self autoLabelString2:tableView string:content.text].height + 30;
            }
        }
        
            return  height + 30;
        
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_FILL])
    {
        int height = 200;
        if (_showAnswer) {
            height += 50;
        }
        
        return height;
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_ANSWER_IMAGE])
    {
       // int height = 0 ;
        UIImage * image = _datas[indexPath.section];
        CGSize size = [self autoImage:image];

        
        return size.height + 10 ;
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_ANSWER_AUDIO])
    {
        return 63;
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_EXPLANATION])
    {
        NSArray *arr = _datas[indexPath.section];
        int height = 30;
        for (DDTopicQuestionExplanation *explanation in arr) {
            
            if ([explanation.type isEqualToString:@"TEXT"])
            {
                height += 30;
            }
            else if ([explanation.type isEqualToString:@"IMAGE"]){
                height += 100;
            }
        }
        return height;
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_TIP])
    {
//        NSArray *arr = _datas[indexPath.section];
        int height = 80;
//        for (DDTopicQuestionExplanation *explanation in arr) {
//            
//            if ([explanation.type isEqualToString:@"TEXT"])
//            {
//                height += 30;
//            }
//            else if ([explanation.type isEqualToString:@"IMAGE"]){
//                height += 100;
//            }
//        }
        return height;
    }
    
    return 0;
}


- (CGSize)autoImage:(UIImage *)image
{
    float w = image.size.width/2;
    float h = image.size.height/2;
    if (w > self.tableView.frame.size.width - 10) {
        //tw/th = w/h = c;
        float c = (self.tableView.frame.size.width - 10)/w;
        float tw = self.tableView.frame.size.width - 10;
        float th = h*c;
       
        return CGSizeMake(tw, th);
    }else{
        return CGSizeMake(w, h);
    }
    
}

- (CGSize)autoLabelString2:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(view.frame.size.width - 100,2000);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}
- (CGSize)autoLabelString:(UIView *)view string:(NSString *)s
{
    
    UIFont *font = [UIFont fontWithName:@"Arial" size:17.0];
    
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    
    NSDictionary * attributes = @{NSFontAttributeName : font,
                                  NSParagraphStyleAttributeName : paragraphStyle};
    
    CGSize contentSize = [s boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT)
                                                 options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                              attributes:attributes
                                                 context:nil].size;
    return contentSize;
    
    
    
//    NSDictionary *attribute = @{NSFontAttributeName: font};
//    
//    CGSize retSize = [s boundingRectWithSize:CGSizeMake(320,1000)
//                                             options:
//                      NSStringDrawingTruncatesLastVisibleLine |
//                      NSStringDrawingUsesLineFragmentOrigin |
//                      NSStringDrawingUsesFontLeading
//                                          attributes:attribute
//                                             context:nil].size;
//    return retSize;
//    //设置一个行高上限
//    CGSize size = CGSizeMake(view.frame.size.width - 20,2000);
//    //计算实际frame大小，并将label的frame变成实际大小
//    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
//    return labelsize;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    if ([cell viewWithTag:8889]) {
        [[cell viewWithTag:8889]removeFromSuperview];
    }
    
    
    if ([_keys[indexPath.section] isEqualToString:KEY_IMAGE]) {
        NSArray *array = _datas[indexPath.section];
        //NSInteger num = array.count;
        
//        if (_title.length > 0) {
//            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, self.tableView.frame.size.width-10, [self autoLabelString:self.tableView string:_title].height+40)];
//            titleLabel.text = _title;
//            titleLabel.numberOfLines = 0;
//            [cell.contentView addSubview:titleLabel];
//            //num -- ;
//        }
        
        _imageArray = array;
        
        DDTopicDataCellModel *topicModel = _topic;
        NSArray *questions = topicModel.questions;
        
        float start_X = 5;
        float start_Y = 5;
        //头像
        UIImageView *header_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(start_X, start_Y, 50, 50)];
        //header_imageView.image = [UIImage imageNamed:@"user_header"];
        [header_imageView sd_setImageWithURL:[NSURL URLWithString:topicModel.userAvatarUrl] placeholderImage:[UIImage imageNamed:@"首页列表头像-通用"]options:SDWebImageRefreshCached];
        header_imageView.layer.cornerRadius = 25.0;
        header_imageView.layer.masksToBounds = YES;
        [cell.contentView addSubview:header_imageView];
        
        //姓名，用户名
        UILabel *name_label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:header_imageView sp:10],header_imageView.frame.origin.y+5 , 200, 24)];
        name_label.text = topicModel.userName;
        name_label.textColor = RGB(124,203,203);
        [cell.contentView addSubview:name_label];
        
        //时间
        UILabel *time_label = [[UILabel alloc] initWithFrame:CGRectMake(name_label.frame.origin.x,[self yPostiong:name_label sp:5] , 200, 16)];
        time_label.text = [self convertTime:topicModel.createTime];//@"1天前";
        time_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
        time_label.textColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:time_label];
        
        //类型按钮
        UIButton *typeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        typeButton.frame = CGRectMake(tableView.frame.size.width - 50, name_label.frame.origin.y+5, 50, 18);
        [typeButton setBackgroundImage:[UIImage imageNamed:@"icon_tag"] forState:UIControlStateNormal];
        
        NSString *typeName = topicModel.courseName;//questions.count > 0 ?((DDTopicQuestion *)questions[0]).typeName : @"";
        [typeButton setTitle:typeName forState:UIControlStateNormal];
        
        
        if (typeName) {
            typeButton.frame = CGRectMake(tableView.frame.size.width - [self autoSize:typeButton string:typeName].width, name_label.frame.origin.y+5, [self autoSize:typeButton string:typeName].width, 18);
        }
        
        typeButton.titleLabel.font = [UIFont fontWithName:@"Arial" size:10.0];
        [typeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        ///[typeButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
        //[typeButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [cell.contentView addSubview:typeButton];
        
        //右上角参与人数
        UILabel *number_people_label = [[UILabel alloc] initWithFrame:CGRectMake(tableView.frame.size.width-60,[self yPostiong:name_label sp:3] , 200, 24)];
        number_people_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
        number_people_label.textColor = RGB(128, 128, 128);
        number_people_label.text = [NSString stringWithFormat:@"%@人回答",topicModel.answerNumber];
        [cell.contentView addSubview:number_people_label];
        
        //右上角悬赏金额按钮
        UILabel *gold_label = [[UILabel alloc] initWithFrame:CGRectMake(typeButton.frame.origin.x-(typeButton.frame.size.width/2),  name_label.frame.origin.y+3, 15, 16)];
        gold_label.text = topicModel.reward;
        gold_label.textAlignment = NSTextAlignmentLeft;
        gold_label.font = [UIFont fontWithName:@"Arial" size:12.0f];
        gold_label.textColor = [UIColor orangeColor];
        [cell.contentView addSubview:gold_label];
        
        
        UIImageView *gold_imageview = [[UIImageView alloc] initWithFrame:CGRectMake([self xxPostiong:gold_label sp:5], name_label.frame.origin.y+5, 12, 12)];
        gold_imageview.image = [UIImage imageNamed:@"icon_gold"];
        [cell.contentView addSubview:gold_imageview];
        
        
        int textorImageHeight = CGRectGetMaxY(header_imageView.frame);
        for (int i = 0 ; i < array.count ; i++)
        {
            NSString *url = array[i];
            NSRange range = [url rangeOfString:@"http://"];//判断字符串是否包含
            if (range.length >0)//包含
            {
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, textorImageHeight, tableView.frame.size.width - 20, 300)];
                [imageView sd_setImageWithURL:[NSURL URLWithString:array[i]] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]options:SDWebImageRefreshCached];
                [cell.contentView addSubview:imageView];
                //imageView.contentMode =  UIViewContentModeScaleAspectFill;
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = imageView.frame;
                [button addTarget:self action:@selector(handleSingleTapImage) forControlEvents:UIControlEventTouchUpInside];
                
                textorImageHeight += 300;
                [cell.contentView addSubview:button];
                
            }else{
                NSString * string = array[i];
                
                UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, textorImageHeight, [self autoLabelString:self.tableView string:string].width, [self autoLabelString:self.tableView string:string].height)];
                titleLabel.text = string;
                titleLabel.font = [UIFont fontWithName:@"Arial" size:17.0];
                titleLabel.numberOfLines = 0;
                [cell.contentView addSubview:titleLabel];
                textorImageHeight += [self autoLabelString:self.tableView string:string].height+5;
                //continue;
            }
            
//            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_title?[self autoLabelString:self.tableView string:_title].height+40:5) + (300*(_title?(i-1<0?0:i-1):i)), tableView.frame.size.width - 20, 300)];
//            [imageView sd_setImageWithURL:[NSURL URLWithString:array[i]] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]options:SDWebImageRefreshCached];
//            [cell.contentView addSubview:imageView];
//            //imageView.contentMode =  UIViewContentModeScaleAspectFill;
//            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//            button.frame = imageView.frame;
//            [button addTarget:self action:@selector(handleSingleTapImage) forControlEvents:UIControlEventTouchUpInside];
//            
//            [cell.contentView addSubview:button];
        }
    }

//    else if ([_keys[indexPath.section] isEqualToString:KEY_LABEL])
//    {
//        for (int i = 0 ; i < array.count ; i++)
//        {
//            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10 + (100*i), tableView.frame.size.width-20, 24)];
//            label.text = array[0];
//            [cell.contentView addSubview:label];
//        }
//    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_OPTION])
    {
        NSArray *array = _datas[indexPath.section];
        UILabel *typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 32)];
        typeLabel.text = [NSString stringWithFormat:@"(%@)", _questionType];
        [cell.contentView addSubview:typeLabel];
        
        int height = [self yPostiong:typeLabel sp:10];
        
        for (int i = 0; i < array.count; i++) {
            DDTopicQuestionOption *option = array[i];
            if (_showAnswer ) {
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, height, cell.frame.size.width-20, 38)];
                label.backgroundColor = RGB(10, 222, 222);
                
                if([option.currect isEqualToString:@"1"]&&_selectOption){
                    label.hidden = NO;
                }else{
                    label.hidden = YES;
                }
                    
                
                [_showAnswerLables addObject:label];
                [cell.contentView addSubview:label];
            }
            
            
            
            
            UIButton *optionButton = [UIButton buttonWithType:UIButtonTypeCustom];
            optionButton.frame = CGRectMake(10, height, 38, 38);
            [optionButton setTitle:option.label forState:UIControlStateNormal];
            [optionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            optionButton.tag = i+1000;
           //NSString *sp =  [userDefault setObject:_result forKey:@"result"];
            
            [optionButton addTarget:self action:@selector(optionSelect:) forControlEvents:UIControlEventTouchUpInside];
            [optionButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-选项bg灰"] forState:UIControlStateNormal];
            [optionButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-选项bg橙"] forState:UIControlStateSelected];
            [cell.contentView addSubview:optionButton];
            
            
            for (NSString *store in _storeOptions) {
                if ([optionButton.titleLabel.text isEqualToString:store]) {
                    optionButton.selected = YES;
                }
            }
            
            
            
            if (option.content.count > 0) {
                DDTopicQuestionOptionContent *content = option.content[0];
                if ([content.type isEqualToString:@"TEXT"])
                {
                    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:optionButton sp:10], optionButton.frame.origin.y-5, tableView.frame.size.width-100, [self autoLabelString2:tableView string:content.text].height+30)];
                    label.text = content.text;
                    label.numberOfLines = 0;
                    label.textColor = [UIColor blackColor];
                    [cell.contentView addSubview:label];
                    
                    height += [self autoLabelString2:tableView string:content.text].height+40;
                }
                else if ([content.type isEqualToString:@"IMAGE"])
                {
//                    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake([self xPostiong:optionButton sp:10], optionButton.frame.origin.y+5, 32, 32)];
//                    [imageView sd_setImageWithURL:[NSURL URLWithString:content.url] placeholderImage:[UIImage imageNamed:@"个人中心-人数统计头像"]options:SDWebImageRefreshCached];
//                    [cell.contentView addSubview:imageView];
                    
    
                    OptionImageView *imageView = [[OptionImageView alloc]initWithFrame:CGRectMake([self xPostiong:optionButton sp:10], optionButton.frame.origin.y+5, 32, 32)];
                    [imageView sd_setImageWithURL:[NSURL URLWithString:content.url] placeholderImage:[UIImage imageNamed:@"个人中心-人数统计头像"]options:SDWebImageRefreshCached];
                    imageView.tag = 8889;
                    imageView.url = content.url;
                    imageView.userInteractionEnabled = YES;
                    [cell addSubview:imageView];
                    tableView.delaysContentTouches = NO;
                    tableView.autoresizesSubviews = YES;
                    [cell.contentView bringSubviewToFront:imageView];
                    cell.userInteractionEnabled=YES;
                    
                    height+=42;
                }
            }else{
                height += 54;
            }
        }
        
        if (_showAnswer&&[_questionType isEqualToString:TOPIC_TYPE_MULTISELECT]) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:@"确定" forState:UIControlStateNormal];
            button.frame = CGRectMake(5, height, self.tableView.frame.size.width-10, 40);
            [button setBackgroundColor:RGB(13, 188, 227)];
            button.layer.cornerRadius = 10.0;
            [button addTarget:self action:@selector(displayDouxian:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = indexPath.section;
            [cell.contentView addSubview:button];
        }
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_FILL])
    {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, self.tableView.frame.size.width-10, 24)];
        titleLabel.text = _questionType;
       
        [cell.contentView addSubview:titleLabel];
        
        _fillTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, [self yPostiong:titleLabel sp:5], self.tableView.frame.size.width-10, 150)];
        _fillTextView.layer.borderWidth = 1.0;
        _fillTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _fillTextView.layer.cornerRadius = 10;
        _fillTextView.delegate = self;
        
        if (_result) {
            _fillTextView.text = _result;
        }
        //UFTextViewCustomToolbar *customToolBar = [UFTextViewCustomToolbar new];
        //[RFKeyboardToolbar addToTextView:_fillTextView withButtons:@[customToolBar]];
        
        [cell.contentView addSubview:_fillTextView];
        
        
        if (_showAnswer) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:@"确定" forState:UIControlStateNormal];
            button.frame = CGRectMake(5, [self yPostiong:_fillTextView sp:10], self.tableView.frame.size.width-10, 40);
            [button setBackgroundColor:RGB(13, 188, 227)];
            button.layer.cornerRadius = 10.0;
            [button addTarget:self action:@selector(enableOff:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:button];
            
            _exlabel = [[UILabel alloc] initWithFrame:CGRectMake(button.frame.origin.x, button.frame.origin.y, cell.frame.size.width, 50)];
            _exlabel.text = _question.tip;
            //[cell.contentView addSubview:_exlabel];
            _exlabel.hidden = YES;
        }
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_ANSWER_IMAGE])
    {
        //for (int i = 0; i < array.count; i++) {
        UIImage *image = _datas[indexPath.section];
        CGSize size = [self autoImage:image];
        cell.userInteractionEnabled = YES;
        cell.contentView.userInteractionEnabled = YES;
        DDMediaIV *answerImageView = [[DDMediaIV alloc] initWithFrame:CGRectMake(5,5,size.width, size.height)];
        
        answerImageView.qid = _question.id;
        //answerImageView.tagIndex =  [NSString stringWithFormat:@"%ld",(long)_answerIndex];
        answerImageView.tagIndex =  [NSString stringWithFormat:@"%ld",(long)indexPath.section];
        [answerImageView addMedias];
        answerImageView.popMediaView = ^(CGPoint point)
        {
            //DDMediaVC *mediaVC = [[DDMediaVC alloc] initWithNibName:@"DDMediaVC" bundle:nil];
            //mediaVC.view.frame = CGRectMake(point.x, point.y, 150, 150);
            //[self addSubview:mediaVC.view];
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setValue:[NSString stringWithFormat:@"%f",point.x] forKey:@"x"];
            [dict setValue:[NSString stringWithFormat:@"%f",point.y] forKey:@"y"];
           // [dict setValue:[NSString stringWithFormat:@"%ld",(long)_answerIndex ] forKey:@"index"];
             [dict setValue:[NSString stringWithFormat:@"%ld",(long)indexPath.section ] forKey:@"index"];
            
            [dict setValue:[NSString stringWithFormat:@"%@",_question.id] forKey:@"qid"];
            [dict setValue:[NSString stringWithFormat:@"%ld",(long)_page] forKey:@"page"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"popTagView" object:dict];
            _answerIndex++;
        };
        answerImageView.userInteractionEnabled = YES;
            answerImageView.image = _datas[indexPath.section];
            [cell.contentView addSubview:answerImageView];
        //}
        
        
    }
    else if ([_keys[indexPath.section] isEqualToString:KEY_ANSWER_AUDIO])
    {
        //for (int i = 0; i < array.count; i++) {
        
        UIButton *answerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        answerButton.frame = CGRectMake(5,5,108, 48);
        [answerButton setImage:[UIImage imageNamed:@"play_audio"] forState:UIControlStateNormal];
        [answerButton addTarget:self action:@selector(playAudio:) forControlEvents:UIControlEventTouchUpInside];
        answerButton.tag = indexPath.section;
        [cell.contentView addSubview:answerButton];
        
        UILabel * timeLable = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:answerButton sp:5], 11, 100, 32)];
        NSString *temp = _datas[indexPath.section];
        NSArray *arr = [temp componentsSeparatedByString:@"|"];
        if (arr.count > 0) {
            NSString *s = arr[1];
        timeLable.text = [NSString stringWithFormat:@"%d\"",s.intValue];
        }
        [cell.contentView addSubview:timeLable];
        //}
        _answerIndex++;
    }else if ([_keys[indexPath.section] isEqualToString:KEY_EXPLANATION]){
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, self.tableView.frame.size.width-10, 24)];
        titleLabel.text = @"作答解析";
        
        [cell.contentView addSubview:titleLabel];
       
        NSArray *arr = _datas[indexPath.section];
        int height = [self yPostiong:titleLabel sp:5];
        for (DDTopicQuestionExplanation *explanation in arr) {
            if ([explanation.type isEqualToString:@"TEXT"])
            {
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, height, tableView.frame.size.width-100, 24)];
                label.text = explanation.text;
                label.textColor = [UIColor blackColor];
                [cell.contentView addSubview:label];
                height += 30;
            }
            else if ([explanation.type isEqualToString:@"IMAGE"])
            {
                UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, height, self.tableView.frame.size.width-20, 100)];
                [imageView sd_setImageWithURL:[NSURL URLWithString:explanation.url] placeholderImage:[UIImage imageNamed:@"个人中心-人数统计头像"]options:SDWebImageRefreshCached];
                [cell.contentView addSubview:imageView];
            }
        }
    }else if ([_keys[indexPath.section] isEqualToString:KEY_TIP]){
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, self.tableView.frame.size.width-10, 24)];
        titleLabel.text = @"作答提示";
        
        [cell.contentView addSubview:titleLabel];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, [self yPostiong:titleLabel sp:10], tableView.frame.size.width-100, 24)];
        label.text = _question.tip;
        label.textColor = [UIColor blackColor];
        [cell.contentView addSubview:label];
        
//        NSArray *arr = _datas[indexPath.section];
//        int height = [self yPostiong:titleLabel sp:5];
//        for (DDTopicQuestionExplanation *explanation in arr) {
//            if ([explanation.type isEqualToString:@"TEXT"])
//            {
//                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, height, tableView.frame.size.width-100, 24)];
//                label.text = explanation.text;
//                label.textColor = [UIColor blackColor];
//                [cell.contentView addSubview:label];
//                height += 30;
//            }
//            else if ([explanation.type isEqualToString:@"IMAGE"])
//            {
//                UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, height, self.tableView.frame.size.width-20, 100)];
//                [imageView sd_setImageWithURL:[NSURL URLWithString:explanation.url] placeholderImage:[UIImage imageNamed:@"个人中心-人数统计头像"]options:SDWebImageRefreshCached];
//                [cell.contentView addSubview:imageView];
//            }
//        }
    }
    return cell;
    
}

- (void)displayDouxian:(UIButton *)sender
{
    sender.hidden = YES;
    NSInteger tag = sender.tag;
    if (_datas > 0) {
        NSArray *array = _datas[tag];
        for (int i= 0 ; i < array.count ; i++) {
            DDTopicQuestionOption *option =array[i];
            NSString *currect = option.currect;
            if ([currect isEqualToString:@"1"]) {
              UILabel *label =  [_showAnswerLables objectAtIndex:i];
                label.hidden = NO;
            }
        }
    }
    _selectOption = YES;
    NSArray *arr = _question.explanation;
    if(arr.count > 0){
        if (![_keys containsObject:KEY_EXPLANATION]) {
            [_datas addObject:_question.explanation];
            [_keys addObject:KEY_EXPLANATION];
            [self.tableView reloadData];
            
        }
    }

}

- (void)enableOff:(UIButton *)sender
{
    sender.hidden = YES;
    [_fillTextView resignFirstResponder];
    _fillTextView.editable = NO;
    _fillTextView.enablesReturnKeyAutomatically = NO;
    _fillTextView.canCancelContentTouches = YES;
    _exlabel.hidden = NO;
    
    NSArray *arr = _question.explanation;
    if(arr.count > 0){
        if (![_keys containsObject:KEY_EXPLANATION]) {
            [_datas addObject:_question.explanation];
            [_keys addObject:KEY_EXPLANATION];
            [self.tableView reloadData];
            
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"clearTagView" object:nil];
}
-(void)playAudio:(UIButton *)sender
{
  NSInteger section = sender.tag;
  NSString *temp = _datas[section];
    NSArray *arr = [temp componentsSeparatedByString:@"|"];
    if (arr.count > 0) {
        if (self.avPlay.playing) {
            [self.avPlay stop];
            return;
        }
        NSURL *url = [[NSURL alloc] initFileURLWithPath:arr[0]];
        AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
        self.avPlay = player;
        [self.avPlay play];
    }
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@",@"123");
}


#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 输出点击的view的类名
    NSLog(@"%@", NSStringFromClass([touch.view class]));
    
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

#pragma mark - textviewDelegate
- (void)textViewDidChangeSelection:(UITextView *)textView{
    NSLog(@"textViewDidChangeSelection:");
    _result = textView.text;
    _storeText =textView.text;
}

#pragma mark - 私用方法
-(void)optionSelect:(UIButton *)button
{
    if ([_questionType isEqualToString:TOPIC_TYPE_SINGLE_SELECTION] || [_questionType isEqualToString:TOPIC_TYPE_JUDGMENT]||[_questionType isEqualToString:@"判断题"]) {
        if (_showAnswer) {
            _selectOption = YES;
        }
        for (int i = 0; i < _question.options.count ; i++) {
            UIButton *otherButton = (UIButton*)[button.superview viewWithTag:1000+i];
            otherButton.selected = NO;
        }
        if (_showAnswer) {
            NSArray *arr = _question.explanation;
            if(arr.count > 0){
                if (![_keys containsObject:KEY_EXPLANATION]) {
                    [_datas addObject:_question.explanation];
                    [_keys addObject:KEY_EXPLANATION];
                    [self.tableView reloadData];
                    
                }
                
            }
        }
        
        
    }
    
    if (_showAnswer) {
      
        for (int i = 0; i < 7 ; i++) {
            UIButton *otherButton = (UIButton*)[button.superview viewWithTag:1000+i];
            if (otherButton != button) {
                //otherButton.enabled = NO;
            }
        }
        
        NSArray *array = @[@"A",@"B",@"C",@"D",@"F",@"G"];
        for (int i = 0; i < 6 ; i++) {
            UIButton *otherButton = (UIButton*)[button.superview viewWithTag:1000+i];
            NSString *ss =  _question.answer;
            NSString *optionStr = array[i];
            if ([optionStr isEqualToString:ss]) {
                 [otherButton setBackgroundImage:[UIImage imageNamed:@"首页-答疑-客观题-圆点选中_09"] forState:UIControlStateNormal];
                if (_showAnswerLables.count > i) {
                    UILabel *label = _showAnswerLables[i];
                     label.hidden = NO;
                }
            }
        }
    }
    
    
    
    button.selected = !button.selected;
    _result = button.titleLabel.text;//[NSString stringWithFormat:@"%ld",button.tag - 1000];
    
    if (button.selected) {
        [_storeOptions addObject:_result];
        if ([_questionType isEqualToString:TOPIC_TYPE_MULTISELECT]) {
            NSString *tempStr = @"";
            for (NSString *str in _storeOptions) {
                tempStr = [NSString stringWithFormat:@"%@%@",tempStr,str];
            }
            _result = tempStr;
        }
    }else{
        [_storeOptions removeObject:_result];
    }
    
    NSUserDefaults *userDefault =  [NSUserDefaults standardUserDefaults];
    [userDefault setObject:_result forKey:@"result"];
}

-(void)handleSingleTapImage
{
    NSLog(@"123123");
    _photos = [NSMutableArray array];
    
    for (int i = 0; i < _imageArray.count ; i++) {
        NSString *url = _imageArray[i];
        NSRange range = [url rangeOfString:@"http://"];//判断字符串是否包含
        if (range.length >0)//包含
        {
            MWPhoto   *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
            //photo.caption = _friendInfo.username;
            [_photos addObject:photo];
        }else{
            continue;
        }
    }
    
     [[NSNotificationCenter defaultCenter]  postNotificationName:@"DisPlayImage" object:_photos];

    // Create browser
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.zoomPhotosToFill = YES;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
    browser.wantsFullScreenLayout = YES;
#endif
    browser.enableSwipeToDismiss = YES;
    [browser setCurrentPhotoIndex:0];
    
    
    //[self addSubview:browser.view];
    
    //[_controller presentViewController:browser animated:YES completion:nil];
    //UIViewController *controller = [self getCurrentVC];
    //[controller presentViewController:browser animated:YES completion:nil];
    //[_controller.navigationController pushViewController:browser animated:YES];
}
#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photos.count)
        return [self.photos objectAtIndex:index];
    return nil;
}
//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}


-(float) xPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.width+view.frame.origin.x + sp;
}

-(float) yPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.height+view.frame.origin.y + sp;
}

- (NSString *)convertTime:(NSString *)time
{
    if (!time || [@"" isEqualToString:time]) {
        return @"";
    }
    
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //用[NSDate date]可以获取系统当前时间
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:time.longLongValue/1000];
    NSString *dateStr = [dateFormatter stringFromDate:d];
    return dateStr;
    
    return @"";
}

- (CGSize)autoSize:(UIView *)view string:(NSString *)s
{
    UIFont *font = [UIFont fontWithName:@"Arial" size:17];
    //设置一个行高上限
    CGSize size = CGSizeMake(1000,44);
    //计算实际frame大小，并将label的frame变成实际大小
    CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
    return labelsize;
}

-(float) xxPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.origin.x - view.frame.size.width -  sp;
}

#pragma mark - Debug

- (NSString *)description {
    return [NSString stringWithFormat:@"[MyCustomViewClass]"];
}

@end
